"""
语音生成快速修复补丁
直接应用到你的 run_interactive.py

使用方法:
python apply_speech_fix.py
"""

import re
from pathlib import Path


def apply_speech_fix():
    """应用语音生成修复"""
    
    print("\n" + "="*70)
    print("🎙️ 应用语音生成修复")
    print("="*70)
    
    target_file = Path("run_interactive.py")
    if not target_file.exists():
        print(f"❌ 找不到文件: {target_file}")
        return False
    
    # 备份
    backup_file = target_file.with_suffix('.py.speech_backup')
    import shutil
    shutil.copy2(target_file, backup_file)
    print(f"✅ 已备份到: {backup_file}")
    
    # 读取文件
    with open(target_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查是否已应用
    if 'stage_5_5_generate_speech' in content:
        print("⚠️ 已应用过此补丁")
        return True
    
    # 添加语音生成方法
    speech_method = '''
    def stage_5_5_generate_speech(self, pages: list) -> bool:
        """阶段5.5: 生成语音"""
        self.interactive.print_header("🎙️ 阶段5.5: 生成语音")
        
        # 检查配置
        speech_config = self.config.get('speech_generation')
        if not speech_config:
            self.interactive.print_warning("未配置语音生成")
            return False
        
        # 检查目录
        speech_dir = self.story_dir / "speech"
        speech_dir.mkdir(parents=True, exist_ok=True)
        
        # 检查已存在的文件
        existing = list(speech_dir.glob("p*.wav"))
        if existing and len(existing) >= len(pages):
            if self.interactive.get_yes_no(
                f"检测到 {len(existing)} 个语音文件，是否使用？", True
            ):
                self.interactive.print_success("使用已存在的语音")
                return True
        
        # 询问是否生成
        if not self.interactive.get_yes_no("开始生成语音？", True):
            self.interactive.print_warning("跳过语音生成")
            return False
        
        try:
            # 使用 MMStoryAgent 生成
            self.interactive.print_info("正在生成语音...")
            
            from mm_story_agent.base import init_tool_instance
            speech_agent = init_tool_instance(speech_config)
            
            params = speech_config.get('params', {}).copy()
            params['pages'] = pages
            params['save_path'] = speech_dir
            
            result = speech_agent.call(params)
            
            # 检查结果
            generated = list(speech_dir.glob("p*.wav"))
            
            if generated:
                self.interactive.print_success(
                    f"语音生成完成: {len(generated)}/{len(pages)}"
                )
                return True
            else:
                self.interactive.print_warning("未生成语音文件")
                return False
                
        except Exception as e:
            self.interactive.print_error(f"语音生成失败: {e}")
            import traceback
            traceback.print_exc()
            return False
'''
    
    # 找到 stage_5_generate_images 方法的位置
    pattern = r'(def stage_5_generate_images\(self.*?\n(?:.*?\n)*?        return images)'
    
    match = re.search(pattern, content, re.MULTILINE)
    if not match:
        print("❌ 找不到 stage_5_generate_images 方法")
        return False
    
    # 在 stage_5_generate_images 方法后插入
    insert_pos = match.end()
    modified_content = (
        content[:insert_pos] + 
        '\n' + speech_method + '\n' +
        content[insert_pos:]
    )
    
    # 修改 run() 方法，添加语音生成调用
    # 找到: image_paths = self.stage_5_generate_images(prompts, pages)
    # 在其后添加: speech_generated = self.stage_5_5_generate_speech(pages)
    
    run_pattern = r'(image_paths = self\.stage_5_generate_images\(prompts, pages\))'
    
    replacement = r'''\1
        
        # 🔥 新增：阶段5.5 - 语音生成
        speech_generated = self.stage_5_5_generate_speech(pages)
        if not speech_generated:
            self.interactive.print_warning("未生成语音，视频将使用默认时长")'''
    
    modified_content = re.sub(run_pattern, replacement, modified_content)
    
    # 写入文件
    with open(target_file, 'w', encoding='utf-8') as f:
        f.write(modified_content)
    
    print("✅ 补丁应用成功！")
    print("\n新增功能：")
    print("  • 在图像生成后自动生成语音")
    print("  • 支持检查已存在的语音文件")
    print("  • 自动处理生成失败的情况")
    
    return True


def verify_speech_config():
    """验证语音配置"""
    print("\n" + "="*70)
    print("🔍 验证语音配置")
    print("="*70)
    
    config_file = Path("configs/config_topic.yaml")
    if not config_file.exists():
        print(f"⚠️ 配置文件不存在: {config_file}")
        return False
    
    import yaml
    with open(config_file, 'r', encoding='utf-8') as f:
        config = yaml.load(f, Loader=yaml.FullLoader)
    
    speech_config = config.get('speech_generation')
    
    if not speech_config:
        print("❌ 配置中未找到 speech_generation")
        return False
    
    print("✅ 找到语音配置")
    print(f"\n配置详情:")
    print(f"  工具: {speech_config.get('tool')}")
    
    params = speech_config.get('params', {})
    print(f"  音色: {params.get('voice', 'N/A')}")
    
    # 检查密钥
    keys = ['access_key_id', 'access_key_secret', 'app_key']
    for key in keys:
        value = params.get(key, '')
        status = "✅" if value else "❌"
        display = f"{value[:10]}..." if value and len(value) > 10 else value
        print(f"  {status} {key}: {display}")
    
    # 检查是否所有密钥都配置了
    all_configured = all(params.get(key) for key in keys)
    
    if all_configured:
        print("\n✅ 语音配置完整")
        return True
    else:
        print("\n❌ 缺少必要的密钥配置")
        print("\n解决方法：")
        print("1. 运行环境变量设置脚本:")
        print("   . .\\setup_env.ps1")
        print("\n2. 或在配置文件中直接填写密钥")
        return False


def test_speech_generation():
    """测试语音生成"""
    print("\n" + "="*70)
    print("🧪 测试语音生成")
    print("="*70)
    
    try:
        import yaml
        from pathlib import Path
        
        # 加载配置
        config_file = Path("configs/config_topic.yaml")
        with open(config_file, 'r', encoding='utf-8') as f:
            config = yaml.load(f, Loader=yaml.FullLoader)
        
        speech_config = config.get('speech_generation')
        if not speech_config:
            print("❌ 未配置语音生成")
            return False
        
        # 初始化代理
        from mm_story_agent.base import init_tool_instance
        
        print("初始化语音生成器...")
        speech_agent = init_tool_instance(speech_config)
        print("✅ 初始化成功")
        
        # 测试单页生成
        test_dir = Path("test_speech_output")
        test_dir.mkdir(exist_ok=True)
        
        test_text = "这是一个语音生成测试。"
        print(f"\n测试文本: {test_text}")
        print("开始生成...")
        
        params = speech_config.get('params', {}).copy()
        params['pages'] = [test_text]
        params['save_path'] = test_dir
        
        result = speech_agent.call(params)
        
        # 检查结果
        generated = list(test_dir.glob("*.wav"))
        if generated:
            print(f"✅ 测试成功！生成了 {len(generated)} 个文件")
            print(f"   文件位置: {test_dir}")
            return True
        else:
            print("❌ 测试失败：未生成文件")
            return False
            
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """主程序"""
    import sys
    
    print("\n" + "="*70)
    print("🎙️ 语音生成修复工具")
    print("="*70)
    
    print("\n选择操作:")
    print("1. 应用语音生成补丁")
    print("2. 验证语音配置")
    print("3. 测试语音生成")
    print("4. 全部执行")
    
    choice = input("\n请选择 (1-4): ").strip()
    
    if choice == '1' or choice == '4':
        apply_speech_fix()
    
    if choice == '2' or choice == '4':
        verify_speech_config()
    
    if choice == '3' or choice == '4':
        test_speech_generation()
    
    if choice == '4':
        print("\n" + "="*70)
        print("📋 完成总结")
        print("="*70)
        print("\n下一步:")
        print("1. 如果配置验证失败，运行: . .\\setup_env.ps1")
        print("2. 如果测试失败，检查网络和API密钥")
        print("3. 运行完整流程: python run_interactive.py --config configs/config_topic.yaml")
    
    print("\n" + "="*70)


if __name__ == "__main__":
    main()